<?php
namespace app\api\controller;

use app\model\CodeModel;
use app\model\StatisticsModel;
use app\model\UserModel;
use think\App;
use think\facade\Db;

class Login extends Base {

    private $userModel;

    private $statisticsModel;

    private $req;

    private $mobile;

    private $code;

    private $appid;

    private $secret;

    private $superVerifyCode = "999999";


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->req = request()->param();

        $this->header = request()->header();

        $this->code = isset($this->req['code']) ? $this->req['code'] : "";;

        $this->mobile = isset($this->req['mobile']) ? $this->req['mobile'] : "";

        $this->appid = config('wx.appid');

        $this->secret = config('wx.secret');

        $this->userModel = new UserModel();

        $this->codeModel = new CodeModel();

        $this->statisticsModel = new StatisticsModel();
    }
    /*
     * 微信小程序登录
     *
     * */
    public function wxAppLogin(){

        if(empty($this->code)){
            return $this->fail("参数错误：code不能为空");
        }

        $response = $this->getWxUserInfo();

        if(!$response || isset($response['errcode'])){
            return $this->fail("获取openid失败:".$response['errmsg']);
        }

        //可以存储sessionKey
        $this->setSessionKey($response['session_key']);

        if (empty($response['openid'])) {
            return $this->fail("获取openid失败:".$response['errmsg']);
        }

        $userInfo = $this->userModel->getUserCacheByOpenId($response['openid']);

        if(!empty($userInfo) && $userInfo['status'] == -1){
            return $this->fail("账号冻结，请联系客服");
        }

        if(!empty($userInfo)){

            //统计今日登陆
            $this->statisticsModel->todayLogin();

            return $this->succ([
                "userinfo"=>$userInfo,
                "token"=>$userInfo['wx_openid'],
                "sessionKey"=>""
            ],"登录成功");
        }

        //注册用户
        Db::startTrans();
        $uid =  $this->userModel->registerUser($response['openid'],"","WXAPP");
        $userInfo = $this->userModel->getUserCacheByOpenId($response['openid']);
        if ($uid && $userInfo) {
            Db::commit();

            //统计今日登陆
            $this->statisticsModel->todayLogin();
            $this->statisticsModel->todayRegister();

            $this->succ([
                "userinfo"=>$userInfo,
                "token"=>$response['openid'],
                "sessionKey"=>$response['session_key']
            ],"注册成功");
        } else {
            Db::rollback();
            return $this->fail("注册失败，请重试");
        }
    }


    /*
     * 保存用户信息
     *
     * */
    public function updateUserInfo(){

        if(empty($this->req)){
            return $this->fail("请求为空");
        }

        $this->uid = $this->isLogin();


        if($this->userModel->checkMobileIsRegister($this->uid,$this->mobile)){
            return $this->fail("手机号已被注册");
        }


        Db::startTrans();
        $res = $this->userModel->updateUserInfoByWxUid($this->uid,$this->req);
        if ($res) {
            Db::commit();
            $this->userModel->delUserCacheByUid($this->uid);
            $userInfo = $this->userModel->getUserInfoByUid($this->uid);
            return $this->succ([
                "userinfo"=>$userInfo,
                "token"=>$userInfo["wx_openid"]
            ]);
        } else {
            Db::rollback();
            return $this->fail("更新失败");
        }
    }



    /*
     * 强制登录
     * */
    public function forceLogin(){
        $user = $this->userModel->getUserCacheByOpenId($this->req['openid']);

        return $this->succ([
            "userinfo"=>$user,
            "token"=>$user['wx_openid']
        ]);
    }


    /*
     * 获取用户信息
     * */
    private function getWxUserInfo(){
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=". $this->appid."&secret=".$this->secret."&js_code=".$this->code."&grant_type=authorization_code";
        return json_decode(file_get_contents($url), true);
    }





    /*
     * 存储session_key
     *
     * */
    private function setSessionKey($sessionKey){
        return session("sessionKey",$sessionKey);
    }


    /*
     * 获取sessionkey
     *
     * */

    private function getSessionKey($sessionKey){
        return session("sessionKey");
    }

}